package com.sky.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.stereotype.Service;

import java.security.Security;
import java.time.LocalDateTime;
import java.util.List;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: EmployeeServiceImpl
 * USER: SHINIAN
 * DATE: 2022/12/12
 * DESCRIPTION : B端-员工信息服务层接口实现类
 */
@Slf4j
@Service
public class EmployeeServiceImpl implements EmployeeService {

    //注入员工持久层实现类Bean(MyBatis生成的代理对象)
    @Autowired
    private EmployeeMapper employeeMapper;
    //修改员工数据
    @Override
    public void updateEmp(Employee employee) {
        employeeMapper.updateEmp(employee);
    }
    //修改密码
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Long empId = BaseContext.getCurrentId();
        Employee employeeById = employeeMapper.getEmployeeById(empId);
        String oldPassword = SecureUtil.md5(passwordEditDTO.getOldPassword());
        String newPassword = SecureUtil.md5(passwordEditDTO.getNewPassword());
        Employee employee = Employee.builder().password(newPassword).id(passwordEditDTO.getEmpId()).build();
        if (!employeeById.getPassword().equals(oldPassword)) {
            throw new PasswordErrorException("初始密码错误");
        }else if(employeeById.getPassword().equals(oldPassword)){
            throw new PasswordEditFailedException("与原密码相同");
        }
        employeeMapper.updateEmp(employee);
    }

    //根据员工id查询
    @Override
    public Employee selectById(Long id) {
      Employee employee = employeeMapper.getEmployeeById(id);
      log.info("=======打印员工信息{}",employee.toString());
        return employee;
    }


    //员工分页查询
    @Override
    public PageResult selectPage(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> pageResult= employeeMapper.selectPage(employeePageQueryDTO);
        long total = pageResult.getTotal();
        List<Employee> employeeList =pageResult.getResult();
        return PageResult.builder().total(total).records(employeeList).build();
    }

    //新增员工基本信息 json文件
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();
        //BeanUtils.copyProperties效率不高，BeanCopier效率更高
        BeanUtils.copyProperties(employeeDTO,employee);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(SecureUtil.md5(PasswordConstant.DEFAULT_PASSWORD));
        employeeMapper.addEmployee(employee);
    }

    /**
     * 员工登录方法
     *
     * @param employeeLoginDTO 员工登录信息的DTO(用户名+密码)
     * @return 查询到的员工信息
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        //获取参数中的用户名与密码
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        //根据用户名查询数据库中的数据
        Employee employee = employeeMapper.selectEmployeeByUsername(username);
        //处理异常情况（用户名不存在）与（密码不对）
        if (employee == null) {
            //账号不存在则抛出对应异常交给全局异常处理器处理
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //处理异常情况（密码错误）
        if (!SecureUtil.md5(password).equals(employee.getPassword())) {
            //密码错误则抛出对应异常交给全局异常处理器处理
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //处理异常情况（用户状态为禁用）
        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定则抛出对应异常交给全局异常处理器处理
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //执行到此处说明以上判断均失败员工信息合法正确则返回实体对象
        return employee;
    }
}
